import React, { Component } from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Spin, message } from 'antd';
import {
  WeaAlertPage,
  WeaLocaleProvider,
  WeaPopoverHrm,
  WeaTools,
  WeaErrorPage,
  WeaNewScroll,
  WeaAvatar,
} from 'ecCom';
import { getFileTypeCls } from '../../util/index';
import ContentIframe from '../com/ContentIframe';
import StaticCollapse from './StaticCollapse';
import StaticReadList from './StaticReadList';

const { tryCatch, viewer } = WeaTools;
const getLabel = WeaLocaleProvider.getLabel;
const MAILPAGENAME = 'STAITVIEW';
/* 邮件审批静态查看页面 */
@tryCatch(
  React,
  props => (
    <WeaErrorPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaErrorPage@e0a2c6`}
      msg={
        props.error ||
        getLabel(186, '对不起，该页面异常，请联系管理员！', 'error')
      }
    />
  ),
  { error: '' },
)
@inject('staticViewStore')
@observer
class StaticView extends Component {
  constructor(props) {
    super(props);
    this.prefixCls = 'email-static-view';
  }

  componentWillMount() {
    const { location, staticViewStore } = this.props;
    const { getViewRight } = staticViewStore;
    const mailId = location.query.mailId || '';
    getViewRight({ mailId });
  }

  componentWillReceiveProps(nextProps) {
    const {
      location: {
        query: { mailId: _id },
      },
      staticViewStore: { getViewRight },
    } = this.props;
    const {
      location: {
        query: { mailId: _idn },
      },
    } = nextProps;
    if (_id !== _idn) getViewRight({ mailId: _idn });
  }

  componentWillUnmount() {
    const { staticViewStore } = this.props;
    staticViewStore.clear();
  }

  listArray = (arr) => {
    let tempArr = arr.map((item) => {
      if (item.showName === '' && item.type === 'group') {
        item.showName = getLabel('506456', '(该组已被删除)');
      }
      return item;
    });
    return tempArr;
  };

  renderBase = (staticViewBean) => {
    const {
      staticViewStore: { staticIsSimple, setStoreState },
    } = this.props;
    const {
      fromSpan,
      senddate,
      ccSpan,
      bccTipInfo,
      bccSpan,
      toSpan,
      subject,
      isInternal,
      fileInfos: { count },
    } = staticViewBean;
    const { imageUrl, showName, hrmId } = fromSpan;
    let list = [
      <div className={`${this.prefixCls}-base-send`}>
        <div className="user-base-info">
          <WeaAvatar
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaAvatar@4b7wkh@${MAILPAGENAME}avatar`}
            url={imageUrl || ''}
            name={showName || ''}
            style={{ width: 40, height: 40 }}
          />
          {hrmId !== '1' && isInternal ? (
            [
              <WeaPopoverHrm
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaPopoverHrm@ljvn9h@${MAILPAGENAME}${hrmId}`}
              />,
              <a
                href={`javaScript:openhrm(${hrmId});`}
                onClick={e => window.pointerXY(e)}
                title={showName}
              >
                {showName}
              </a>,
            ]
          ) : (
            <span className="userName">{showName}</span>
          )}
          <span className="senddate">{senddate}</span>
        </div>
        <div className={`${this.prefixCls}-base-send-ops`}>
          {/* eslint-disable */}
          <span
            className="isSimple"
            onClick={() =>
              setStoreState({ staticIsSimple: staticIsSimple ^ 1 })
            }
          >
            {staticIsSimple
              ? getLabel(34223, "完整")
              : getLabel(384288, "精简")}
            {getLabel(33361, "信息")}{" "}
            <i className={`icon-coms-${staticIsSimple ? "down" : "up"}`} />
          </span>
          {/* eslint-enable */}
        </div>
      </div>,
      <div className={`${this.prefixCls}-base-to`}>
        <span className={`${this.prefixCls}-base-to-title`}>
          {getLabel(2046, '收件人')}:
        </span>
        <StaticCollapse
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_StaticCollapse@vksp2j@${MAILPAGENAME}toSpan`}
          ref="collapseTo"
          datas={this.listArray(toJS(toSpan.list))}
          isInternal={isInternal}
        />
      </div>,
    ];
    ccSpan &&
      ccSpan.list &&
      ccSpan.list.length > 0 &&
      !staticIsSimple &&
      list.push(
        <div className={`${this.prefixCls}-base-to`}>
          <span className={`${this.prefixCls}-base-to-title`}>
            {getLabel(17051, '抄送人')}:
          </span>
          <StaticCollapse
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_StaticCollapse@ce3cgg@${MAILPAGENAME}ccSpan`}
            ref="collapseCc"
            datas={this.listArray(toJS(ccSpan.list))}
            isInternal={isInternal}
          />
        </div>,
      );
    if (!staticIsSimple) {
      if (bccTipInfo) {
        list.push(
          <div className={`${this.prefixCls}-base-to`}>
            <span className={`${this.prefixCls}-base-to-title`}>
              {getLabel(81316, '密送人')}:
            </span>
            <p style={{ color: 'red' }}>{bccTipInfo}</p>
          </div>,
        );
      } else {
        bccSpan &&
          bccSpan.list &&
          bccSpan.list.length > 0 &&
          !staticIsSimple &&
          list.push(
            <div className={`${this.prefixCls}-base-to`}>
              <span className={`${this.prefixCls}-base-to-title`}>
                {getLabel(81316, '密送人')}:
              </span>
              <StaticCollapse
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_StaticCollapse@xatw93@${MAILPAGENAME}collapseCc`}
                ref="collapseCc"
                datas={this.listArray(toJS(bccSpan.list))}
                isInternal={isInternal}
              />
            </div>,
          );
      }
    }
    list.push(
      <div className={`${this.prefixCls}-base-title`}>
        <span dangerouslySetInnerHTML={{ __html: subject }} />
        {staticViewBean.op_showUnReadedCount ? (
          <span
            className={`${this.prefixCls}-base-title-unreadedcount`}
            onClick={() =>
              this.onUnReadedListClick(
                staticViewBean.id,
                staticViewBean.originalMailId,
              )
            }
          >
            {staticViewBean.unReadedCount}
            {getLabel(384293, '个未查看')}
          </span>
        ) : null}
      </div>,
    );
    count > 0 &&
      list.push(
        <div className={`${this.prefixCls}-base-files`}>
          {getLabel(18609, '共')}
          {count} {getLabel(83077, '个附件')}
          <a onClick={() => this.refs.scroll.scrollToLast()}>
            {getLabel(83124, '查看附件')}
          </a>
        </div>,
      );
    return <div className={`${this.prefixCls}-base`}>{list}</div>;
  };

  renderFiles = (datas) => {
    const { fileList, count, totalSizeStr, batchDownloadUrl } = datas;
    if (count === 0) return null;
    return (
      <div className={`${this.prefixCls}-files`}>
        <div className={`${this.prefixCls}-files-title`}>
          <i className="icon-email-Enclosure" />
          {getLabel(156, '附件')}
          {count} {getLabel(27591, '个')}
          <span
            className={`${this.prefixCls}-files-title-batch-download`}
            onClick={() => window.open(batchDownloadUrl)}
          >
            <span>
              <i className="icon-coms-download" />
              {getLabel(32407, '批量下载')}
            </span>
            <span>({totalSizeStr})</span>
          </span>
        </div>
        <div className={`${this.prefixCls}-files-list`}>
          {toJS(fileList).map((file) => {
            const {
              filelink,
              previewUrl,
              filename,
              filesize,
              fileid,
              isImg,
              fileExtendName,
            } = file;
            return (
              <div className={`${this.prefixCls}-files-list-item`} key={fileid}>
                <div className={`${this.prefixCls}-files-list-item-img`}>
                  {isImg === 'true' ? (
                    /* eslint-disable */
                    <img
                      data-imgsrc={previewUrl}
                      ref={fileid}
                      src={previewUrl}
                      width={56}
                      height={56}
                      className="formImgPlay"
                      style={{ borderRadius: 4, cursor: "pointer" }}
                      onClick={viewer}
                    />
                  ) : (
                    /* eslint-enable */
                    <i
                      className={getFileTypeCls(fileExtendName)}
                      onClick={() => this.previewFile(file)}
                    />
                  )}
                </div>
                <div className={`${this.prefixCls}-files-list-item-content`}>
                  {isImg === 'true' ? (
                    <p title={filename}>{filename}</p>
                  ) : (
                    /* eslint-disable */
                    <p title={filename} onClick={() => this.previewFile(file)}>
                      {filename}
                    </p>
                    /* eslint-enable */
                  )}
                  <p>{filesize}</p>
                </div>
                <div className={`${this.prefixCls}-files-list-item-ops`}>
                  <i
                    className="icon-coms-download"
                    title={getLabel(31156, '下载')}
                    onClick={() => window.open(filelink)}
                  />
                  <i
                    className="icon-email-Save-the-cloud-disk"
                    style={{ display: 'none' }}
                    title={getLabel(129159, '保存到云盘')}
                  />
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  };

  previewFile = (file) => {
    const { staticViewStore } = this.props;
    const { staticViewBean } = staticViewStore;
    const { unPreview } = staticViewBean;
    if (unPreview == '1') {
      // 禁止预览
      message.warning(getLabel('520702', '后台邮件系统设置,禁止附件预览'));
    } else {
      const previewurl = `/spa/email/static/index.html#/main/preview?fileid=${file.id}`;
      openFullWindowHaveBar(previewurl);
    }
  };

  getAlertPage = (iconCls, text) => (
    <div className={this.prefixCls}>
      <WeaAlertPage
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaAlertPage@7ud7oa`}
        icon={<i className={iconCls} style={{ color: '#999' }} />}
        iconSize={40}
      >
        <div style={{ color: '#999', marginTop: 16 }}>{text}</div>
      </WeaAlertPage>
    </div>
  );

  onUnReadedListClick = (mailId, originalMailId) => {
    const { staticViewStore } = this.props;
    const { getReadCount, getReadList, setStoreState } = staticViewStore;
    let params = {
      mailId,
      originalMailId,
      readed: '',
    };
    getReadCount(params);
    getReadList(params);
    setStoreState({ staticReadListVisible: true });
  };

  hide = () => {
    const { collapseTo, collapseCc } = this.refs;
    collapseTo && collapseTo.hide();
    collapseCc && collapseCc.hide();
  };

  render() {
    const { staticViewStore } = this.props;
    const {
      staticLoading,
      staticViewRight,
      staticViewBean,
      staticMailContent,
    } = staticViewStore;
    if (staticLoading) {
      return (
        <div className={this.prefixCls}>
          <Spin
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Spin@urquqj`}
            size="large"
          />
        </div>
      );
    }
    if (!staticLoading && staticViewRight * 1 !== 1) {
      return this.getAlertPage(
        'icon-email-error',
        getLabel(385529, '无权查看该邮件'),
      );
    }
    return (
      <div className={this.prefixCls}>
        <Spin
          ecId={`${(this && this.props && this.props.ecId) || ''}_Spin@qqfh8s`}
          spinning={staticLoading}
        >
          <WeaNewScroll
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaNewScroll@bv654h`}
            height="100%"
            toTop
            ref="scroll"
            onScroll={this.hide}
          >
            {this.renderBase(toJS(staticViewBean))}
            <div className={`${this.prefixCls}-content`}>
              <ContentIframe
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_ContentIframe@pjkx7g`}
                ref="content"
                value={toJS(staticMailContent)}
              />
            </div>
            {staticViewBean.fileInfos &&
              this.renderFiles(staticViewBean.fileInfos)}
            <StaticReadList
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_StaticReadList@8of19x`}
            />
          </WeaNewScroll>
        </Spin>
      </div>
    );
  }
}
export default StaticView;
